package com.gxa.modules.sys.controller;

import com.gxa.modules.sys.entity.OperationLog;
import com.gxa.modules.sys.form.ExcelUtil;
import com.gxa.modules.sys.service.OperationLogService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Api(tags = "文件导出 接口")
@RestController
@Slf4j
public class ExportController {
    @Autowired
    private OperationLogService operationLogService;
    /**
     * 导出报表
     *
     * @return
     */
    @PostMapping(value = "/export")
    @ResponseBody
    public String export(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取数据
        List<OperationLog> operationLogs = this.operationLogService.queryAll();

        System.out.println("operationLogs-------->"+operationLogs);
        //excel标题
        //根据sql语句查询的字段名添加
        String[] title = {"操作时间", "操作人", "操作模块", "操作内容"};

        //excel文件名
        String fileName = "操作日志" + System.currentTimeMillis() + ".xls";

        //sheet名
        String sheetName = "操作日志";

        String [][] content = new String[operationLogs.size()][12];
        //根据字段名添加数据（String类型）
        for (int i = 0; i < operationLogs.size(); i++) {
            content[i] = new String[title.length];
            OperationLog obj=operationLogs.get(i);

            String date = String.valueOf(obj.getOperatingTime());

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = sdf.format(Date.parse(date));
            System.out.println(time);


            content[i][0] = time;
            content[i][1] = obj.getUser().getName();
            content[i][2] = obj.getOperationModule();
            content[i][3] = obj.getOperationContent();
        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);

        //响应到客户端，可以自己选择保存路径E:\Test
        try {
            FileOutputStream out = new FileOutputStream("E:\\Test\\"+fileName);
            wb.write(out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ok";
    }

}
